<?php
/**
 * OrderProductRepo.php
 *
 * @copyright  2023 beikeshop.com - All Rights Reserved
 * @link       https://beikeshop.com
 * @author     TL <mengwb@guangda.work>
 * @created    2023-06-12 15:22:05
 * @modified   2023-06-12 15:22:05
 */

namespace Beike\Seller\Repositories;

use Beike\Models\Order;
use Illuminate\Database\Eloquent\Builder;

class OrderProductRepo extends \Beike\Repositories\OrderProductRepo
{
    /**
     * 创建商品明细
     *
     * @param Order $order
     * @param $cartProducts
     */
    public static function createOrderProducts(Order $order, $cartProducts)
    {
        $orderProducts = [];
        foreach ($cartProducts as $cartProduct) {
            $productName   = $cartProduct['name'];
            $variantLabels = $cartProduct['variant_labels'] ?? '';
            if ($variantLabels) {
                $productName .= " - {$variantLabels}";
            }
            $orderProducts[] = [
                'order_id'                 => $order->id,
                'product_id'               => $cartProduct['product_id'],
                'order_number'             => $order->number,
                'product_sku'              => $cartProduct['product_sku'],
                'name'                     => $productName,
                'image'                    => $cartProduct['image'],
                'quantity'                 => $cartProduct['quantity'],
                'price'                    => $cartProduct['price'],
                'seller_id'                => $cartProduct['seller_id']                ?? 0,
                'store_commission_flat'    => $cartProduct['store_commission_flat']    ?? 0,
                'store_commission_percent' => $cartProduct['store_commission_percent'] ?? 0,
                'seller_amount'            => $cartProduct['seller_amount']            ?? 0,
                'created_at'               => now(),
                'updated_at'               => now(),
            ];
        }
        \Beike\Seller\Models\OrderProduct::query()->insert($orderProducts);
    }

    public static function getBuilder(array $filters = [], $sellerId = null): Builder
    {
        $builder = parent::getBuilder($filters);
        if ($sellerId === null) {
            $sellerId = current_seller_user()->seller_id ?? 0;
        }
        if ($sellerId) {
            $builder->whereHas('order', function ($query) use ($sellerId) {
                $query->where('seller_id', $sellerId);
            });
        }

        return $builder;
    }
}
